#include"Queue.h"

Queue* QueueCreate()
{
	Queue* q = (Queue*)malloc(sizeof(Queue));
	if (NULL == q)
	{
		perror("malloc failed");
		exit(-1);
	}
	q->head = q->tail = NULL;
	q->size = 0;
	return q;
}

void QueueDestroy(Queue* q)
{
	assert(q);
	while (!QueueEmpty(q))
		QueuePop(q);
	free(q);
}

void QueuePush(Queue* q, QDataType x)
{
	assert(q);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (NULL == newnode)
	{
		perror("malloc failed");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	if (QueueEmpty(q))
		q->head = q->tail = newnode;
	else
	{
		q->tail->next = newnode;
		q->tail = newnode;
	}
	++(q->size);
}

QDataType QueuePop(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	QDataType ret = q->head->data;
	QNode* newhead = q->head->next;
	free(q->head);
	q->head = newhead;
	if (NULL == newhead)
		q->tail = NULL;
	--(q->size);
	return ret;
}

QDataType QueueFront(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	return q->head->data;
}

QDataType QueueBack(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	return q->tail->data;
}

int QueueSize(Queue* q)
{
	assert(q);
	return q->size;
}

bool QueueEmpty(Queue* q)
{
	assert(q);
	return !(q->size);
}
